#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量将代码文件转换为UTF-8编码
"""

import os
import sys
import chardet
from pathlib import Path

def detect_encoding(file_path):
    """检测文件编码"""
    try:
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            return result['encoding'], result['confidence']
    except Exception as e:
        print(f"检测编码失败 {file_path}: {e}")
        return None, 0

def convert_to_utf8(file_path):
    """将文件转换为UTF-8编码"""
    try:
        # 检测当前编码
        encoding, confidence = detect_encoding(file_path)
        
        if encoding is None:
            print(f"无法检测编码: {file_path}")
            return False
            
        print(f"文件: {file_path}")
        print(f"  当前编码: {encoding} (置信度: {confidence:.2f})")
        
        # 如果已经是UTF-8，跳过
        if encoding.lower() in ['utf-8', 'utf8'] and confidence > 0.8:
            print(f"  已经是UTF-8编码，跳过")
            return True
            
        # 读取文件内容
        try:
            with open(file_path, 'r', encoding=encoding, errors='ignore') as f:
                content = f.read()
        except UnicodeDecodeError:
            # 如果检测的编码失败，尝试其他常见编码
            encodings_to_try = ['gbk', 'gb2312', 'big5', 'latin-1', 'cp1252']
            content = None
            for enc in encodings_to_try:
                try:
                    with open(file_path, 'r', encoding=enc) as f:
                        content = f.read()
                        encoding = enc
                        break
                except:
                    continue
                    
            if content is None:
                print(f"  无法读取文件内容")
                return False
        
        # 以UTF-8编码保存
        with open(file_path, 'w', encoding='utf-8', newline='') as f:
            f.write(content)
            
        print(f"  已转换为UTF-8编码")
        return True
        
    except Exception as e:
        print(f"转换失败 {file_path}: {e}")
        return False

def main():
    """主函数"""
    # 获取脚本目录
    script_dir = Path(__file__).parent
    scripts_dir = script_dir / "Assets" / "Scripts"
    
    if not scripts_dir.exists():
        print(f"脚本目录不存在: {scripts_dir}")
        return
    
    # 统计信息
    total_files = 0
    converted_files = 0
    skipped_files = 0
    failed_files = 0
    
    print("开始转换代码文件为UTF-8编码...")
    print("=" * 50)
    
    # 遍历所有.cs文件
    for cs_file in scripts_dir.rglob("*.cs"):
        total_files += 1
        print(f"\n处理文件 {total_files}: {cs_file.relative_to(script_dir)}")
        
        try:
            success = convert_to_utf8(cs_file)
            if success:
                # 检查是否真的需要转换
                encoding, confidence = detect_encoding(cs_file)
                if encoding.lower() in ['utf-8', 'utf8'] and confidence > 0.8:
                    if total_files <= 5:  # 只对前几个文件显示详细信息
                        print(f"  确认: 现在是UTF-8编码")
                    converted_files += 1
                else:
                    failed_files += 1
            else:
                failed_files += 1
        except Exception as e:
            print(f"处理文件时出错: {e}")
            failed_files += 1
    
    print("\n" + "=" * 50)
    print("转换完成!")
    print(f"总文件数: {total_files}")
    print(f"成功转换: {converted_files}")
    print(f"跳过文件: {skipped_files}")
    print(f"失败文件: {failed_files}")

if __name__ == "__main__":
    main()
